<?php

/**
 * 案件调解
 * @author HelloWorld
 * UTF-8
 */
class CallinfoController extends Controller_Base
{

    //拨打电话
    public function callAction()
    {
        $request = $this->getRequest();

        $caseId = $request->getPost('caseId', '');
        $phone = $request->getPost('phone', '');
        $uuid = $request->getPost('uuid', '');
        $callId = $request->getPost('callId', '');
        if (empty($caseId) || empty($phone) || empty($callId)) {
            AjaxTool::returnJsonData(4005);
        }
        Lib_Redis_Hash::hSet("CALL_" . $callId,'caseId',$caseId);
        Lib_Redis_Hash::hSet("CALL_" . $callId,'phone',$phone);
        Lib_Redis_Hash::expire("CALL_" . $callId,3600);
        AjaxTool::returnJsonData(200);

    }
    //拨打电话
    public function searchCaseinAction()
    {
        $request = $this->getRequest();

        $search = $request->getPost('search', '');
        if(empty($search)){
            AjaxTool::returnJsonData(4005);
        }
        $where = [];
        //是否为手机号
        if(Lib_CheckData::checkMobile($search)){
            array_push($where,"telephone = {$search}");
        }
        //是否为身份证号
        if(Lib_CheckData::checkCard($search)){
            array_push($where,"cardId = '{$search}'");
        }
        //是否有中文
        if(preg_match("/[\\x7f-\\xff]/", $search)){
            array_push($where,"litigantName = '{$search}'");
        }

        if($where){
            $litigants = Module_Mediate_CaseLitigant::getInstance()->getAllBySearch(['caseId','litigantName','cardId',],['where'=>$where,'group'=>'caseId']);
            if($litigants){
                $y = date('Y');
                $mediationNum = SmartyAdapter::getTplVars('mediationNum');
                foreach ($litigants as $key => $val){
                    $litigants[$key]['cardId'] = substr($val['cardId'] , 0 , 6) .'******'. substr($val['cardId'], -4);
                    $litigants[$key]['mediateNum'] = "（{$y}）{$mediationNum}{$val['caseId']}号";
                }
            }
        }
        AjaxTool::returnJsonData(200,'success',$litigants);

    }
    //呼叫详情
    public function caseinfoAction(){
        $request = $this->getRequest();
        $id = $request->getPost('caseId', 0);
        $callId = $request->getPost('callId', '');
        if($callId){
            Lib_Redis_String::setex("CALL-CASEID" .$callId, 1800, $id);
        }
        $fieldType = $request->getPost('fieldType', '');
        if(empty($id)){
            AjaxTool::returnJsonData(4005);
        }
        $case = Module_Mediate_Case::getInstance()->getItemById($id);
        if(empty($case)){
            AjaxTool::returnJsonData(400,'未查询到案件信息');
        }
        //判断是否是一人多案
        if($case['caseLabel'] == 1){
            //查询同一批次同一个人的案件
            $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['*'],['where'=>["importRecordId={$case['importRecordId']}","cardId='{$case['cardId']}'"]]);
            if(empty($cases)){
                AjaxTool::returnJsonData(400,'未查询到案件信息');
            }
        }else{
            //查询同一批次同一个人的案件
            $cases[] = $case;
        }
        $case_ids = implode(',',array_column($cases,'id'));

        $attach = Module_Mediate_CaseAttach::getInstance()->getAllBySearch(['*'],['where'=>["caseId in ({$case_ids})"]],true);
        $case_attach = array_column($attach,NULL,'caseId');
        $fields = Lib_Var::$excel_title['caseDetail'];
        $case_info = [];
        $overdueMonth = 0;
        $caseNum = count($cases);
        $debtAmount = $debtInte = $debtTotal = $claimAmount = 0;
        foreach ($cases as $case){
            $debtAmount = bcadd($debtAmount,$case['debtAmount'],2);
            $debtInte = bcadd($debtInte,$case['debtInte'],2);
            $debtTotal = bcadd($debtTotal,$case['debtTotal'],2);
            $claimAmount = bcadd($claimAmount,$case['claimAmount'],2);
            $debtTotal = bcadd($debtTotal,$case['debtTotal'],2);
            $showFields = [
                '案件号'=>$case['id'],
                '逾期期数M'=>$case['overdueMonth'],
                '调解案号'=>$case['mediationNum'],
                '案件标识号'=>$case['batshId'],
            ];
            if($case['overdueMonth'] > $overdueMonth){
                $overdueMonth = $case['overdueMonth'];
            }
            foreach ($fields as $key => $field){
                if(!in_array($key,['litigantName','cardId','telephone'])){
                    if(!empty($field['check']) && $field['check'] == 'checkDate'){
                        $showFields[preg_replace('/\(.*?\)|\（.*?\）/', '', $field['name'])] = !empty($case[$key])?date("Y/m/d H:i:s",$case[$key]):'';
                    }else{
                        $showFields[preg_replace('/\(.*?\)|\（.*?\）/', '', $field['name'])] = $case[$key];
                    }
                }
            }
            if(isset($case_attach[$case['id']])){
                $attachInfo = json_decode($case_attach[$case['id']]['attachInfo'],true);
                if($attachInfo){
                    foreach ($attachInfo as $val){
                        if(empty($val['val'])){
                            continue;
                        }
                        $showFields[$val['key']] = $val['val'];
                    }
                }

            }
            $showFields['调解员'] = $case['mediatorName'];

            if (count($showFields) % 2 != 0) {
                $showFields['']='';
            }
            $case_info[$case['id']] = $showFields;

        }
        $litigantName = $case['litigantName'];
        $cardId = Func_Common::getInstance()->ID_to_encrypt($case['cardId']);
        $sex = Func_Common::getInstance()->ID_to_sex($case['cardId']);
        $age = Func_Common::getInstance()->ID_to_age($case['cardId']);
        $showCardId = $case['cardId'];
        if (strpos($case['litigantName'], ',') !== false) {
            $litigantName = '';
            $cardId = '';
            $showCardId = '';
            $sex = '';
            $age = '';
            $litigants = Module_Mediate_CaseLitigant::getInstance()->getAllBySearch(['*'], ['where' => ["caseId = {$id}",'isDel=0'],'order'=>'id DESC','group'=>'cardId']);
            foreach ($litigants as $litigant){
                $litigantName .= $litigant['litigantName'].',';
                $cardId .= Func_Common::getInstance()->ID_to_encrypt($litigant['cardId'])."<br>";
                $sex .= Func_Common::getInstance()->ID_to_sex($litigant['cardId']).',';
                $age .= Func_Common::getInstance()->ID_to_age($litigant['cardId']).',';
                $showCardId .= $litigant['cardId'].',';
            }
        }

        $mediateResult = Module_Mediate_Case::$mediateResult;
        array_pop($mediateResult);
        $return = [
            'case_id' => $id,
            'header_case' => [
                'litigantName' => trim($litigantName,','),
                "pingyin_litigantName" => Lib_Pinyin::getInstance()->convert($litigantName),
                'cardId'=> trim($cardId,','),
                'sex'=> trim($sex,','),
                'age'=> trim($age,','),
                'showCardId'=> trim($showCardId,','),
                'caseMainInfo'=> "案件：{$caseNum} 宗；欠款总本金：".number_format($debtAmount,2)." 元；欠款总利息：".number_format($debtInte,2)." 元；欠款总额：".number_format($claimAmount,2)." 元；",
                'debtTotal' => number_format($claimAmount,2),
                'customLabel' => $case['customLabel'],
                'customGrade' => $case['customGrade'],
                'repayStatus' => Module_Mediate_Case::$repayStatusArr[$case['repayStatus']],
                'mediateResult' => Module_Mediate_Case::$mediateResult[$case['mediateResult']],
                'caseType'=>Module_Mediate_Case::$caseType[$case['caseType']],
                'overdueMonth'=>$overdueMonth,
                'mediationNum'=>$case['mediationNum']
            ],
            'case_info' => $case_info,
            'business_data' => 1,
            'case' => $case,
            'mediateResult' => $mediateResult,
            'repayStatus' => Module_Mediate_Case::$repayStatusArr,
            'customLabel' => Module_Mediate_Case::$customLabel,
            'customGrade' => Module_Mediate_Case::$customGrade,
            'mobileStatus' => Module_Mediate_CaseLitigant::$mobileStatus,
            'fieldType' => $fieldType
        ];
        AjaxTool::returnJsonData(200,'',$return);

    }
    //获取当前案件的下一个案件id
    public function getNextidAction(){
        $case_id = $this->_request->getPost('caseId',0);
        $direction = $this->_request->getPost('direction');
        $fieldType = $this->_request->getPost('fieldType');
        $sort_key = "{$fieldType}_Cases_".$this->admin['id'];
        $current_index = Lib_Redis_SortedSet::zScore($sort_key,$case_id);
        if(!$current_index){
            $case = Module_Mediate_Case::getInstance()->getItemById($case_id);
            if(empty($case)){
                AjaxTool::returnJsonData(400,'未查询到案件信息');
            }
            //判断是否是一人多案
            if($case['caseLabel'] == 1){
                //查询同一批次同一个人的案件
                $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['id'],['where'=>["importRecordId={$case['importRecordId']}","cardId='{$case['cardId']}'"]]);
                if(empty($cases)){
                    AjaxTool::returnJsonData(400,'未查询到案件信息');
                }
                foreach ($cases as $case){
                    if(Lib_Redis_SortedSet::zScore($sort_key,$case['id'])){
                        $current_index = Lib_Redis_SortedSet::zScore($sort_key,$case['id']);
                    }
                }
            }
        }
        if($direction == 'prev'){
            $next_id = Lib_Redis_SortedSet::zRangeByScore($sort_key,$current_index-1,$current_index-1);
        }else{
            $next_id = Lib_Redis_SortedSet::zRangeByScore($sort_key,$current_index+1,$current_index+1);
        }
        if(empty($next_id['0'])){
            AjaxTool::returnJsonData(400,'没有啦！');

        }
        AjaxTool::returnJsonData(200,'',['caseId'=>$next_id['0']]);
    }
    //获取电话号码
    public function getMobileAction()
    {
        $request = $this->getRequest();
        //案件id
        $case_id = $request->getPost('caseId', 0);

        if (empty($case_id)) {
            AjaxTool::returnJsonData(4005);
        }
        $case = Module_Mediate_Case::getInstance()->getItemById($case_id, true);
        if(empty($case)){
            AjaxTool::returnJsonData(400,'未查询到案件信息');
        }
        $isFlashsms = 0;
        //查询案件批次是否支持闪信
        $importRecord = Module_Mediate_EntryImport::getInstance()->getItemById($case['importRecordId'], true);
        if(!empty($importRecord)){
            $isFlashsms = $importRecord['isFlashsms'];
        }
        $assets = Module_InfoBase_Assets::getInstance()->getItemById($case['assetsId'], true);
        $litigant = Module_Mediate_CaseLitigant::getInstance()->getAllBySearch(['*'], ['where' => ["cardId = '{$case['cardId']}' ",'isDel=0'],'order'=>'id DESC','group'=>'telephone']);
        $case_mobile = [];
        //修复成功
        $workerId = SmartyAdapter::getTplVars('workerId');
        $outNumber = $workerId > 7000 ? $assets['outNumber'] : $assets['outNumber2'];
        $businessData = empty($outNumber) ? $isFlashsms : $isFlashsms.'-'.$outNumber;
        if($case['ydRepairStatus'] == 1 || $case['ltRepairStatus'] == 1  ){
            $repair_mobile = Module_Repair_RepairResult::getInstance()->getAllBySearch(['*'],['where'=>["idCard='{$case['cardId']}'"]]);
            if($repair_mobile){
                foreach ($repair_mobile as $mobile){
                    $temp = array(
                        'mobileId' => $mobile['id'],
                        'telephone' => $mobile['repairmobile'],
                        'enTelephone' => $mobile['repairType'] == 1 ? substr($mobile['repairmobile'], 0, 6).'****' : $mobile['repairmobile'],
                        'mobileSource' => $mobile['repairType'] == 1 ? '移动修复' : "联通修复",
                        'statusDesc' =>  Module_Mediate_CaseLitigant::$mobileStatus[$mobile['mobileStatus']],
                        'mobileStatus' =>  $mobile['mobileStatus'],
                        'area' =>  '未知',
                        'isShow' =>  $mobile['mobileStatus'] == 1 ? 1 : 0,
                        'mobileType' =>  $mobile['repairType'] == 1 ? 2 : 3,
                        'businessData' =>  $businessData,
                    );
                    array_push($case_mobile, $temp);
                }
            }
        }
        if($litigant){
            foreach ($litigant as $mobile) {
                $temp = array(
                    'mobileId' => $mobile['id'],
                    'telephone' => $mobile['telephone'],
                    'enTelephone' => substr_replace($mobile['telephone'], '****', 3, 4),
                    'mobileSource' => Module_Mediate_CaseLitigant::$mobileSource[$mobile['mobileSource']],
                    'statusDesc' =>  Module_Mediate_CaseLitigant::$mobileStatus[$mobile['mobileStatus']],
                    'mobileStatus' =>  $mobile['mobileStatus'],
                    'area' =>  '北京移动',
                    'isShow' =>  $mobile['mobileStatus'] == 1 ? 1 : 0,
                    'mobileType' =>  1,
                    'businessData' =>  $businessData,
                );
                array_push($case_mobile, $temp);
            }
        }


        $keysValue = [];
        foreach ($case_mobile as $k => $v) {
            $keysValue[$k] = $v['isShow'];
        }
        array_multisort($keysValue, SORT_DESC, $case_mobile);
        AjaxTool::returnJsonData(200, '成功', $case_mobile);

    }
    //修改案件属性
    public function updateAttributeAction()
    {
        $request = $this->getRequest();
        //案件id
        $caseId = $request->getPost('caseId', 0);
        $attribute = $request->getPost('attribute', '');
        $attributeVal = $request->getPost('attributeVal', 0);
        if (empty($caseId) || empty($attribute) || $attributeVal === '') {
            AjaxTool::returnJsonData(4005);
        }
        if(!in_array($attribute,['customLabel','customGrade'])){
            AjaxTool::returnJsonData(4005);
        }
        if(!in_array($attributeVal,array_keys(Module_Mediate_Case::$$attribute))){
            AjaxTool::returnJsonData(4005);
        }
        $case = Module_Mediate_Case::getInstance()->getItemById($caseId);
        if (empty($case)) {
            AjaxTool::returnJsonData(4005);
        }
        //统计有效案件
        if($attribute == 'customLabel'){
            //个人有效案件
            $workerId = SmartyAdapter::getTplVars('workerId');
            if($workerId){
                if($attributeVal == 1){
                    Lib_Redis_Hash::hIncrby($workerId,'effective',1);
                }
                if($attributeVal != 1 && $case['customLabel'] == 1){
                    Lib_Redis_Hash::hIncrby($workerId,'effective',-1);
                }
            }
            //项目有效
            if($attributeVal == 1){
                Lib_Redis_Hash::hIncrby($case['assetsId'],'effective',1);
            }
            if($attributeVal != 1 && $case['customLabel'] == 1){
                Lib_Redis_Hash::hIncrby($case['assetsId'],'effective',-1);
            }
        }
        //判断是否是一人多案
        if($case['caseLabel'] == 1){
            //查询同一批次同一个人的案件
            $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['*'],['where'=>["importRecordId={$case['importRecordId']}","cardId='{$case['cardId']}'"]],true);
            if(empty($cases)){
                AjaxTool::returnJsonData(400,'未查询到案件信息');
            }
        }else{
            //查询同一批次同一个人的案件
            $cases[] = $case;
        }
        $case_ids = implode(',',array_column($cases,'id'));

        $res = Module_Mediate_Case::getInstance()->saveByIds(
            [
                'updateTime'=>time(),
                $attribute=>$attributeVal,
            ],
            $case_ids
        );
        $val =  Module_Mediate_Case::$$attribute[$attributeVal];
        if($attribute == 'customLabel'){
            $data = [
                'caseId' => $case['id'],
                'status' => 'update_case_attr',
                'operationUid' => $this->admin['id'],
                'operationName' => $this->admin['name'],
                'operationContent' => "更新用户标签",
                'remark' => "更新用户标签为【{$val}】",
                'createTime' => time(),
            ];
        }else{
            $data = [
                'caseId' => $case['id'],
                'status' => 'update_case_attr',
                'operationUid' => $this->admin['id'],
                'operationName' => $this->admin['name'],
                'operationContent' => "更新用户等级",
                'remark' => "更新用户等级为【{$val}】",
                'createTime' => time(),
            ];
        }
        $post_data = [
            'type' => 'Module_Task_Case',
            'method' => 'addOperateLog',
            'data' => $data
        ];
        @Module_Queue_Base::addQueue($post_data);

        if ($res) {
            AjaxTool::returnJsonData(200,'操作成功');
        }
        AjaxTool::returnJsonData(400,'操作失败');

    }
    //修改号码状态
    public function phoneUpdateAction()
    {
        $request = $this->getRequest();
        //案件id
        $mobileId = $request->getPost('mobileId', 0);
        $mobileStatus = $request->getPost('mobileStatus', 0);
        $mobileType = $request->getPost('mobileType', 1);
        if (empty($mobileId) || empty($mobileStatus) || empty($mobileType)) {
            AjaxTool::returnJsonData(4005);
        }
        if(!in_array($mobileStatus,array_keys(Module_Mediate_CaseLitigant::$mobileStatus))){
            AjaxTool::returnJsonData(4005);
        }
        if($mobileType == 1){
            $mobile = Module_Mediate_CaseLitigant::getInstance()->getItemById($mobileId, false);
            if (empty($mobile)) {
                AjaxTool::returnJsonData(4005);
            }
            $res = Module_Mediate_CaseLitigant::getInstance()->updateMobileStatusByCardIDMobile($mobileStatus,$mobile['cardId'],$mobile['telephone']);
        }else{
            $res = Module_Repair_RepairResult::getInstance()->singleUpdate(
                [
                    'id'=>$mobileId,
                    'mobileStatus'=>$mobileStatus,
                ]
            );
        }
        if ($res) {
            AjaxTool::returnJsonData(200,'操作成功');
        }
        AjaxTool::returnJsonData(400,'操作失败');

    }
    //修改号码
    public function phoneDeleteAction()
    {
        $request = $this->getRequest();
        //案件id
        $mobileId = $request->getPost('mobileId', 0);
        if (empty($mobileId) ) {
            AjaxTool::returnJsonData(4005);
        }
        $mobile = Module_Mediate_CaseLitigant::getInstance()->getItemById($mobileId, false);
        if (empty($mobile)) {
            AjaxTool::returnJsonData(4005);
        }
        $res = Module_Mediate_CaseLitigant::getInstance()->singleUpdate(
            [
                'id'=>$mobileId,
                'isDel'=>1,
            ]
        );
        if ($res) {
            AjaxTool::returnJsonData(200,'操作成功');
        }
        AjaxTool::returnJsonData(400,'操作失败');

    }
    //添加号码
    public function phoneAddAction()
    {
        $request = $this->getRequest();
        //案件id
        $caseId = $request->getPost('caseId', 0);
        $telephone = $request->getPost('telephone', '');
        if (!$this->checkMobile($telephone) ) {
            AjaxTool::returnJsonData(4005,'请填写正确的号码');
        }
        //判断是否存在
        $history = Module_Mediate_CaseLitigant::getInstance()->getOne(['*'],["caseId = $caseId","telephone = $telephone AND isDel = 0"]);
        if ($history) {
            AjaxTool::returnJsonData(4005,'该号码已存在');
        }

        //litigant = Module_Mediate_CaseLitigant::getInstance()->getOne(['*'],["caseId = $caseId order by id DESC"]);
        $litigant = Module_Mediate_Case::getInstance()->getOne(['litigantName,cardId'],["id = $caseId"]);
        if (empty($litigant)) {
            AjaxTool::returnJsonData(4005);
        }
        $res = Module_Mediate_CaseLitigant::getInstance()->singleInsert(
            [
                'caseId' => $caseId,
                'litigantName' => $litigant['litigantName'],
                'cardId' => $litigant['cardId'],
                'telephone' => $telephone,
                'mobileSource' => 3,
            ]
        );
        if ($res) {
            AjaxTool::returnJsonData(200,'操作成功');
        }
        AjaxTool::returnJsonData(400,'操作失败');

    }
    //添加还款计划
    public function addReturnedMoneyPlanAction(){
        $request = $this->getRequest();
        //案件id
        $caseId = $request->getPost('caseId', 0);
        $returnedMoney = $request->getPost('returnedMoney', 0);
        $returnedDay = $request->getPost('returnedDay', 0);
        $returnedDetail= $request->getPost('returnedDetail', []);
        if(empty($caseId) || empty($returnedMoney) || empty($returnedDay) || empty($returnedDetail)){
            AjaxTool::returnJsonData(4005);
        }
        $case = Module_Mediate_Case::getInstance()->getItemById($caseId);
        if(empty($case)){
            AjaxTool::returnJsonData(4005);
        }
        $history = Module_Mediate_ReturnedMoneyPlan::getInstance()->getOne(['id'],["mediatorId = {$this->admin['id']}","caseId = {$caseId}"]);
        if($history){
            AjaxTool::returnJsonData(4005,'该案件下您已添加还款计划，请修改还款计划或删除重新添加');
        }
        $now = time();
        foreach ($returnedDetail as $key => $detail){
            if(empty($detail['returnedTime']) || empty($detail['returnedMoney'])){
                $term = $key + 1;
                AjaxTool::returnJsonData(4005,"第{$term}期参数错误");
            }
            $savePlanDetail[] = [
                'mediatorId' => $this->admin['id'],
                'mediatorName' => $this->admin['name'],
                'mediationOrganId' => $this->admin['mediationOrganId'],
                'assetsId' => $case['assetsId'],
                'status' => 'keep_plan',
                'addTime' => $now,
                'updateTime' => $now,
                'caseId' => $caseId,
                'repayAmount' => $detail['returnedMoney'],
                'repaymentDate' => strtotime($detail['returnedTime']),
                'litigantName' => $case['litigantName'],
            ];
        }
        //入库
        $savePlan = [
            'mediatorId' => $this->admin['id'],
            'mediatorName' => $this->admin['name'],
            'mediationOrganId' => $this->admin['mediationOrganId'],
            'assetsId' => $case['assetsId'],
            'batshId' => $case['batshId'],
            'importRecordId' => $case['importRecordId'],
            'status' => 'wait_repay',
            'addTime' => $now,
            'updateTime' => $now,
            'caseId' => $caseId,
            'repayAmount' => $returnedMoney,
            'numberOfPayments' => count($returnedDetail),
            'repaymentDate' => $returnedDay,
            'litigantName' => $case['litigantName'],
        ];
        $res = Module_Mediate_ReturnedMoneyPlan::getInstance()->insert($savePlan,$savePlanDetail);
        if(!$res){
            AjaxTool::returnJsonData(200,'操作失败');

        }
        if($case['repayStatus'] != 'no_repay'){
            Module_Mediate_ReturnedMoneyPlan::getInstance()->cancelRepay($this->admin['id'],$caseId);
        }
        //操作日志
        $insertdata = array(
            'caseId' => $caseId,
            'status' => "entry_repay",
            'operationUid' => $this->admin['id'],
            'operationName' => $this->admin['name'],
            'operationContent' => '添加还款计划,还款金额：'.$savePlan['repayAmount'].',还款期数：'.$savePlan['numberOfPayments'],
            'createTime' => time(),
        );
        Module_Mediate_CaseOperationLog::getInstance()->insert($insertdata);

        AjaxTool::returnJsonData(200,'操作成功');

    }
    //获取调解历史
    public function getMediationLogAction(){
        $request = $this->getRequest();
        $caseId = $request->getPost('caseId', 0);
        if(empty($caseId)){
            AjaxTool::returnJsonData(4005);
        }
        $case = Module_Mediate_Case::getInstance()->getItemById($caseId, true);
        if (empty($case)) {
            AjaxTool::returnJsonData(4005);
        }
        //判断是否是一人多案
        if($case['caseLabel'] == 1){
            //查询同一批次同一个人的案件
            $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['*'],['where'=>["importRecordId={$case['importRecordId']}","cardId='{$case['cardId']}'"]],true);
            if(empty($cases)){
                AjaxTool::returnJsonData(400,'未查询到案件信息');
            }
        }else{
            //查询同一批次同一个人的案件
            $cases[] = $case;
        }
        $case_ids = array_column($cases,'id');
        $mediateLogs =[];
        $keysValue = [];
        foreach ($case_ids as $caseId){

            $mediateLog = Module_Mediate_CaseMediateLog::getInstance()->getMediateLogByCaseId($caseId);
            if($mediateLog){
                foreach ($mediateLog as $key => &$log){

                    $log['caesId'] =  $caseId;
                    $log['addTime'] =  date("Y/m/d H:i:s",$log['addTime']);
                    $log['type'] =  $log['mediateType'] == 1 ? ($log['type'] == 1 ? "呼出" : '呼入') : '';
                    $log['mediateResult'] =  Module_Mediate_Case::$mediateResult[$log['mediateResult']];
                    $log['mobile'] =  $log['mobile'] ? substr_replace($log['mobile'], '****', 3, 4) : '';
                    $log['nextTime'] =  $log['nextTime'] ? date("Y/m/d",$log['nextTime']) : 0;
                    $log['fileName'] =  $log['fileName'] ? SmartyAdapter::getTplVars('soundfileurl').$log['fileName'] : '';
                    $log['mediateType'] =  Module_Mediate_CaseMediateLog::$mediateType[$log['mediateType']];
                    $log['mobile'] = Module_Mediate_CaseMediateLog::$mobileType[$log['mobileType']] . ' ' .$log['mobile'];

                    $mediateLogs[] = $log;
                    $keysValue[] = $log['addTime'];

                }
            }
        }
        array_multisort($keysValue, SORT_DESC, $mediateLogs);
        AjaxTool::returnJsonData(200,'操作成功',$mediateLogs);

    }
    //获取短信历史
    public function getSMSLogAction(){
        $request = $this->getRequest();
        $caseId = $request->getPost('caseId', 0);
        if(empty($caseId)){
            AjaxTool::returnJsonData(4005);
        }
        $case = Module_Mediate_Case::getInstance()->getItemById($caseId, true);
        if (empty($case)) {
            AjaxTool::returnJsonData(4005);
        }
        //判断是否是一人多案
        if($case['caseLabel'] == 1){
            //查询同一批次同一个人的案件
            $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['*'],['where'=>["importRecordId={$case['importRecordId']}","cardId='{$case['cardId']}'"]],true);
            if(empty($cases)){
                AjaxTool::returnJsonData(400,'未查询到案件信息');
            }
        }else{
            //查询同一批次同一个人的案件
            $cases[] = $case;
        }
        $case_ids = implode(',',array_column($cases,'id'));
        $smsLog = Module_Mediate_SmsRecord::getInstance()->getAllBySearch([],['where'=>["caseId in ($case_ids)"],'order'=>"id DESC"]);
        if($smsLog){
            foreach ($smsLog as $key => $log){
                $smsLog[$key]['caseId'] =  $log['caseId'];
                $smsLog[$key]['sendTime'] =  date("Y/m/d H:i:s",$log['sendTime']);
                $smsLog[$key]['sendStatus'] = $log['sendStatus'] == 1 ? "成功" : ( $log['sendStatus'] == 2 ? "发送中":'失败');
                $smsLog[$key]['mobile'] = substr_replace($log['mobile'], '****', 3, 4);
                $smsLog[$key]['scene'] = Lib_SMS_Config::$smsCode[$log['scene']];
            }
        }
        AjaxTool::returnJsonData(200,'操作成功',$smsLog);

    }
    //获取操作日志
    public function getOperateLogAction(){
        $request = $this->getRequest();
        $caseId = $request->getPost('caseId', 0);
        if(empty($caseId)){
            AjaxTool::returnJsonData(4005);
        }
        $case = Module_Mediate_Case::getInstance()->getItemById($caseId, true);
        if (empty($case)) {
            AjaxTool::returnJsonData(4005);
        }
        //判断是否是一人多案
        if($case['caseLabel'] == 1){
            //查询同一批次同一个人的案件
            $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['*'],['where'=>["importRecordId={$case['importRecordId']}","cardId='{$case['cardId']}'"]],true);
            if(empty($cases)){
                AjaxTool::returnJsonData(400,'未查询到案件信息');
            }
        }else{
            //查询同一批次同一个人的案件
            $cases[] = $case;
        }
        $case_ids = implode(',',array_column($cases,'id'));
        $operateLog = Module_Mediate_CaseOperationLog::getInstance()->getAllBySearch([],['where'=>["caseId in ($case_ids)"],'order'=>"id DESC"]);
        if($operateLog){
            foreach ($operateLog as $key => $log){
                $operateLog[$key]['createTime'] =  date("Y/m/d H:i:s",$log['createTime']);
            }
        }
        AjaxTool::returnJsonData(200,'操作成功',$operateLog);
    }
    //获取还款计划
    public function getReturnedPlanAction(){
        $request = $this->getRequest();
        $caseId = $request->getPost('caseId', 0);
        if(empty($caseId)){
            AjaxTool::returnJsonData(4005);
        }
        if(empty($caseId)){
            AjaxTool::returnJsonData(4005);
        }
        $case = Module_Mediate_Case::getInstance()->getItemById($caseId, true);
        if (empty($case)) {
            AjaxTool::returnJsonData(4005);
        }
        //判断是否是一人多案
        if($case['caseLabel'] == 1){
            //查询同一批次同一个人的案件
            $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['*'],['where'=>["importRecordId={$case['importRecordId']}","cardId='{$case['cardId']}'"]],true);
            if(empty($cases)){
                AjaxTool::returnJsonData(400,'未查询到案件信息');
            }
        }else{
            //查询同一批次同一个人的案件
            $cases[] = $case;
        }
        $case_ids = implode(',',array_column($cases,'id'));
        $plan = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getAllBySearch([],['where'=>["caseId in ($case_ids)","status <> 'cancel_repay'"]]);
        $plans = [];
        if($plan){
//            foreach ($plan as $key => &$log){
//                if(empty( $term[$log['caseId']])){
//                    $term[$log['caseId']] = 1;
//                }else{
//                    $term[$log['caseId']] ++;
//                }
//                $plan[$key]['term'] =  "第 {$term[$log['caseId']]} 期";
//                $plan[$key]['repaymentDate'] =  $log['realRepaymentDate'] ? date("Y/m/d",$log['realRepaymentDate']) :  date("Y/m/d",$log['repaymentDate']);
//                $plan[$key]['repayAmount'] =  $log['realRepayAmount'] * 1 ? $log['realRepayAmount'] : $log['repayAmount'];
//                $plan[$key]['status'] = Module_Mediate_Case::$planStatusArr[$log['status']];
//                $plans[$log['caseId']][] = $plan[$key];
//            }
            foreach ($plan as $key => &$log){
                if(empty( $term[$log['caseId']])){
                    $term[$log['caseId']] = 1;
                }else{
                    $term[$log['caseId']] ++;
                }
                $plan[$key]['term'] =  "第 {$term[$log['caseId']]} 期";
                $plan[$key]['repaymentDate'] =  $log['realRepaymentDate'] ? date("Y/m/d",$log['realRepaymentDate']) :  date("Y/m/d",$log['repaymentDate']);
                $plan[$key]['repayAmount'] =  $log['realRepayAmount'] * 1 ? $log['realRepayAmount'] : $log['repayAmount'];
                $plan[$key]['status'] = Module_Mediate_Case::$planStatusArr[$log['status']];
                $plans[$log['caseId']][] = $plan[$key];
            }
        }
        AjaxTool::returnJsonData(200,'操作成功',$plans);
    }
    //添加调解记录
    public function addMediationLogAction(){
        $request = $this->getRequest();
        $caseId = $request->getPost('caseId', 0);
        $desc = $request->getPost('desc', 0);
        $mediateResult = $request->getPost('mediateResult', '');
        $mediateType = $request->getPost('mediateType', 0);
        $is_sync = $request->getPost('isSync', 0);
        $nextTime = $request->getPost('nextTime', 0);
        $callId = $request->getPost('callId', '');
        $type = $request->getPost('type', 1);
        if(empty($caseId) || empty($mediateResult)){
            AjaxTool::returnJsonData(4005);
        }
        if($mediateResult == 'again_mediate' && empty($nextTime)){
            AjaxTool::returnJsonData(4005,"请填写约定下再次联系的时间");
        }
        if($mediateType == 1 && empty($callId)){
            AjaxTool::returnJsonData(4005,"线上调解必须通话才能保存");
        }
        $case_mediate = [
            'caseId' => $caseId,
            'mediatorId' => $this->admin['id'],
            'mediatorName' => $this->admin['name'],
            'nextTime' => $nextTime ? strtotime($nextTime) : 0,
            'callId' => $callId,
            'type' => $type,
            'mediateResult' => $mediateResult,
            'mediateType' => $mediateType,
            'desc' => $desc,
            'addTime' => time()
        ];
        if(in_array($mediateResult,['accept_mediate','refuse_mediate','unsuitable_mediate'])){
            $mediateStatus = 'finish_mediate';
        }else{
            $mediateStatus = 'in_mediate';
        }
        $update_case = [
            'mediateStatus'=>$mediateStatus,
            'lastCallTime'=>time(),
            'updateTime'=>time()
        ];
        if($is_sync){
            $update_case['mediateResult'] = $mediateResult;
        }
        if($case_mediate['nextTime']){
            $update_case['nextTime'] = $case_mediate['nextTime'];
        }
        $res = Module_Mediate_CaseMediateLog::getInstance()->insert($case_mediate,$update_case);
        if (!$res) {
            AjaxTool::returnJsonData(400,'操作失败');
        }
        AjaxTool::returnJsonData(200,'操作成功');


    }
    //保存投诉建议
    public function saveSuggestionAction()
    {
        $request = $this->getRequest();
        $suggestion =  trim($request->getPost('desc', ''));
        $mainUniqueId =  trim($request->getPost('callId', 0));
        $case_id =  $request->getPost('case_id', 0);
        //参数效验
        if (empty($mainUniqueId) || empty($suggestion)) {
            AjaxTool::returnJsonData(4005);
        }
        $save_data = [
            'operationUid' => $this->admin['id'],
            'operationName' => $this->admin['name'],
            'suggestion' => $suggestion,
            'caseId' => $case_id,
            'callId' => $mainUniqueId,
            'addTime' => time(),
        ];
        $res = Module_Mediate_Suggestion::getInstance()->insert($save_data);
        if($res){
            AjaxTool::returnJsonData(200);
        }
        AjaxTool::returnJsonData(400,'添加失败');
    }

}
